<?php

use EasySwoole\EasySwoole\Logger;

if (!function_exists('dd')) {

    function dd($data, $title = ''): void
    {
        echo '<---------' . $title . ' - ' . date('Y-m-d H:i:s') . '---------->';
        echo PHP_EOL;
        if (gettype($data) == 'boolean') {
            if ($data) {
                echo 'true';
            } else {
                echo 'false';
            }
        } else {
            print_r($data);
        }
        echo PHP_EOL;
        echo '<-----------------end------------------>';
        echo PHP_EOL;
    }

}

if (!function_exists('getIp')) {
    function getIp(): string
    {
        if (getenv('HTTP_CLIENT_IP')) {
            $ip = getenv('HTTP_CLIENT_IP');
        }
        if (getenv('HTTP_X_REAL_IP')) {
            $ip = getenv('HTTP_X_REAL_IP');
        } elseif (getenv('HTTP_X_FORWARDED_FOR')) {
            $ip = getenv('HTTP_X_FORWARDED_FOR');
            $ips = explode(',', $ip);
            $ip = $ips[0];
        } elseif (getenv('REMOTE_ADDR')) {
            $ip = getenv('REMOTE_ADDR');
        } else {
            $ip = '0.0.0.0';
        }
        return $ip;
    }
}

if (!function_exists('logger_info')) {
    function logger_info($message, string $title = ''): void
    {

        if (is_array($message)) {
            Logger::getInstance()->info(($title ? ($title . ' : ') : '') . json_encode($message));
        } else {
            Logger::getInstance()->info(($title ? ($title . ' : ') : '') . $message);
        }

    }
}

if (!function_exists('logger_error')) {
    function logger_error($message, string $title = ''): void
    {
        if (is_array($message)) {
            Logger::getInstance()->error(($title ? ($title . ' : ') : '') . json_encode($message, JSON_UNESCAPED_UNICODE));
        } else {
            Logger::getInstance()->error(($title ? ($title . ' : ') : '') . $message);
        }

    }
}


if (!function_exists('trimAll')) {
    function trimAll($str)
    {
        return is_string($str) ? str_replace(array(" ", "　", "\t", "\n", "\r"), '', $str) : $str;
    }
}


if (!function_exists('hourStep')) {
    function hourStep(): int
    {
        $hour = date('H');
        $step = 0;

        switch ($hour) {
            case 0:
            case 1:
            case 2:
            case 3:
            case 4:
            case 5:
                break;
            case 6:
            case 7:
            case 8:
            case 9:
            case 10:
            case 11:
                $step = 6;
                break;
            case 12:
            case 13:
            case 14:
            case 15:
            case 16:
            case 17:
                $step = 12;
                break;
            case 18:
            case 19:
            case 20:
            case 21:
            case 22:
            case 23:
                $step = 18;
                break;
        }

        return $step;
    }
}

if (!function_exists('hourStepReverse')) {
    function hourStepReverse(): int
    {
        $step = hourStep();

        $preStep = 0;
        switch ($step) {
            case 0:
                $preStep = 12;
                break;
            case 6:
                $preStep = 18;
                break;
            case 12:
                $preStep = 0;
                break;
            case 18:
                $preStep = 6;
                break;
        }

        return $preStep;
    }
}

/**
 * 递归实现无限极分类
 * @param $array 分类数据
 * @param $pid 父ID
 * @param $level 分类级别
 * @return $list 分好类的数组 直接遍历即可 $level可以用来遍历缩进
 */
if (!function_exists('getTree')) {
    function getTree(array $array, int $pid = 0, string $pidName = 'pid', string $idName = 'id', int $level = 0, string $pName = 'name', string $childrenName = 'children', array $p = [], array $saveField = []): array
    {
        $list = array();
        foreach ($array as $v) {

            if ($saveField) {
//                dd($v);
                foreach ($v as $field => $fieldValue) {
                    if (!in_array($field, $saveField)) {
                        unset($v[$field]);
                    }
                }
            }

            if ($v[$pidName] == $pid) {
                $v['parent'] = $v[$pidName] == 0 ? '顶级' : $p[$pName];
//                $v['level'] = $level;
//                $v['show'] = 1;
                $v[$childrenName] = getTree($array, $v[$idName], $pidName, $idName, $level + 1, $pName, $childrenName, $v, $saveField);
                $list[] = $v;
            }
        }
        return $list;
    }
}


/**
 * 验证两个日期是否超过指定天数
 * @param string $date1 第一个日期（格式：Y-m-d）
 * @param string $date2 第二个日期（格式：Y-m-d）
 * @param int $maxDays 最大允许天数（默认90天）
 * @return array 验证结果
 */
if (!function_exists('validateDateRange')) {
    function validateDateRange(string $date1, string $date2, int $maxDays = 90): array
    {
        // 转换为时间戳
        $timestamp1 = strtotime($date1);
        $timestamp2 = strtotime($date2);

        // 验证日期格式
        if ($timestamp1 === false || $timestamp2 === false) {
            return [
                'valid' => false,
                'message' => '日期格式无效，请使用年月日格式'
            ];
        }

        // 计算日期差的绝对值（天数）
        $daysDifference = abs($timestamp2 - $timestamp1) / (60 * 60 * 24);

        // 验证是否超过最大天数
        if ($daysDifference > $maxDays) {
            return [
                'valid' => false,
                'message' => "日期间隔不能超过 {$maxDays} 天"
            ];
        }

        return [
            'valid' => true,
            'message' => "日期间隔验证通过"
        ];
    }
}
